<template>
	<!-- #ifdef APP-NVUE -->
	<cell>
		<slot></slot>
		<view :style="{height: Util.pixelunit(columnGap)}"></view>
	</cell>
	<!-- #endif -->
	<!-- #ifndef APP-NVUE -->
	<view class="yb-waterfall-item yb-flex" ref="ybWaterfallItem" :style="{
		width: Util.pixelunit(realWidth),
		left: left + 'px',
		top: top + 'px'
	}">
		<slot></slot>
	</view>
	<!-- #endif -->
</template>

<script>
	import ComponentMixin from '../../js_sdk/componentMixin.js'
	import Util from '../../js_sdk/util.js'
	export default {
		name: 'YbWaterfallItem',
		mixins: [ComponentMixin],
		computed: {
			Util () {
				return Util
			},
			realWidth () {
				return this.columnWidth == 'auto' ? ( (750 - Util.anytorpx(this.leftGap, false) - Util.anytorpx(this.rightGap, false)) - ((this.columnCount - 1) * Util.anytorpx(this.columnGap, false)) ) / this.columnCount : this.columnWidth
			}
		},
		data () {
			return {
				height: 0,
				left: 0,
				top: 0,
				index: -1,
				columnWidth: 'auto',
				columnGap: 0,
				columnCount: 2,
				listData: [],
				leftGap: 0,
				rightGap: 0
			}
		},
		mounted () {
			this.$nextTick(function () {
				let parent = Util.getParent('YbWaterfall', this);
				this.columnWidth = parent.columnWidth
				this.columnGap = parent.columnGap
				this.columnCount = parent.columnCount
				this.leftGap = parent.leftGap
				this.rightGap = parent.rightGap
				this.listData = parent.listData
			})
		},
		methods: {
			getSize () {
				this.$nextTick(function () {
					Util.getRect('.yb-waterfall-item', this.$refs.ybWaterfallItem, this).then(res => {
						this.computedHeight(res.height)
					})
				})
			},
			//图片加载失败
			onerror () {
				this.computedHeight(200)
			},
			computedHeight (height) {
				let parent = Util.getParent('YbWaterfall', this);
				this.height = height + Util.unitpixel(this.columnGap)
				let minHeight = this.listData[0].height
				for ( let i in this.listData ) {
					minHeight = Math.min(minHeight, this.listData[i].height)
				}
				this.index = this.listData.findIndex(item => item.height == minHeight)
				this.left = this.index * (Util.unitpixel(this.realWidth) + Util.unitpixel(this.columnGap))
				this.top = minHeight
				parent && parent.changeListHeight(this.index, this.height)
			}
		},
		beforeDestroy() {
			// #ifndef APP-NVUE
			let parent = Util.getParent('YbWaterfall', this);
			parent && parent.removeListHeight(this.index, this.height)
			// #endif
		}
	}
</script>

<style scoped>
	.yb-waterfall-item {
		position: absolute;
	}
</style>